<?php
declare (strict_types = 1);

namespace app\controller;

use think\Request;
use think\Response;
use think\facade\Db;
use think\response\Json;

class PurchaseLedger
{
    /**
     * 获取采购台账列表
     */
    public function list(Request $request): Json
    {
        try {
            $page = (int)$request->param('pageNo', 1);
            $limit = (int)$request->param('pageSize', 10);
            $supplier_name = $request->param('supplier_name', '');
            $is_invoiced = $request->param('is_invoiced', '');
            $is_paid = $request->param('is_paid', '');
            
            $where = [];
            
            if (!empty($supplier_name)) {
                $where[] = ['supplier_name', 'like', '%' . $supplier_name . '%'];
            }
            
            if ($is_invoiced !== '') {
                $where[] = ['is_invoiced', '=', $is_invoiced];
            }
            
            if ($is_paid !== '') {
                $where[] = ['is_paid', '=', $is_paid];
            }
            
            $list = Db::name('purchase_ledger')
                ->where($where)
                ->order('create_time desc')
                ->page($page, $limit)
                ->select();
            
            $total = Db::name('purchase_ledger')
                ->where($where)
                ->count();
            
            // 格式化数据
            foreach ($list as &$item) {
                $item['is_invoiced'] = (string)$item['is_invoiced'];
                $item['is_paid'] = (string)$item['is_paid'];
                $item['arrival_date'] = date('Y-m-d', strtotime($item['arrival_date']));
                if ($item['payment_date']) {
                    $item['payment_date'] = date('Y-m-d', strtotime($item['payment_date']));
                } else {
                    $item['payment_date'] = '';
                }
            }
            
            return json([
                'code' => 1,
                'msg' => 'success',
                'data' => [
                    'list' => $list,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit
                ]
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => '获取采购台账列表失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }
    
    /**
     * 保存采购台账（新增/编辑）
     */
    public function save(Request $request): Json
    {
        try {
            $data = $request->param();
            
            // 验证必填字段
            if (empty($data['supplier_name'])) {
                return json(['code' => 0, 'msg' => '供应商名称不能为空']);
            }
            if (empty($data['product_name'])) {
                return json(['code' => 0, 'msg' => '产品名称不能为空']);
            }
            if (empty($data['arrival_date'])) {
                return json(['code' => 0, 'msg' => '到货日期不能为空']);
            }
            if (empty($data['arrival_quantity']) || $data['arrival_quantity'] <= 0) {
                return json(['code' => 0, 'msg' => '到货数量必须大于0']);
            }
            if (!isset($data['is_invoiced'])) {
                return json(['code' => 0, 'msg' => '请选择开票状态']);
            }
            if (!isset($data['is_paid'])) {
                return json(['code' => 0, 'msg' => '请选择付款状态']);
            }
            
            // 准备保存数据
            $saveData = [
                'supplier_name' => $data['supplier_name'],
                'product_name' => $data['product_name'],
                'arrival_date' => $data['arrival_date'],
                'arrival_quantity' => (int)$data['arrival_quantity'],
                'is_invoiced' => (int)$data['is_invoiced'],
                'is_paid' => (int)$data['is_paid'],
                'payment_method' => $data['payment_method'] ?? '',
                'payment_date' => !empty($data['payment_date']) ? $data['payment_date'] : null,
                'remark' => $data['remark'] ?? '',
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            if (!empty($data['id'])) {
                // 编辑
                $result = Db::name('purchase_ledger')
                    ->where('id', $data['id'])
                    ->update($saveData);
                
                if ($result !== false) {
                    return json(['code' => 1, 'msg' => '编辑成功']);
                } else {
                    return json(['code' => 0, 'msg' => '编辑失败']);
                }
            } else {
                // 新增
                $saveData['create_time'] = date('Y-m-d H:i:s');
                
                $result = Db::name('purchase_ledger')->insert($saveData);
                
                if ($result) {
                    return json(['code' => 1, 'msg' => '新增成功']);
                } else {
                    return json(['code' => 0, 'msg' => '新增失败']);
                }
            }
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => '保存失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }
    
    /**
     * 删除采购台账
     */
    public function delete(Request $request): Json
    {
        try {
            $id = $request->param('id');
            
            if (empty($id)) {
                return json(['code' => 0, 'msg' => 'ID不能为空']);
            }
            
            // 支持批量删除
            if (strpos($id, ',') !== false) {
                $ids = explode(',', $id);
                $result = Db::name('purchase_ledger')
                    ->where('id', 'in', $ids)
                    ->delete();
            } else {
                $result = Db::name('purchase_ledger')
                    ->where('id', $id)
                    ->delete();
            }
            
            if ($result) {
                return json(['code' => 1, 'msg' => '删除成功']);
            } else {
                return json(['code' => 0, 'msg' => '删除失败']);
            }
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => '删除失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }
    
    /**
     * 获取采购台账详情
     */
    public function detail(Request $request): Json
    {
        try {
            $id = $request->param('id');
            
            if (empty($id)) {
                return json(['code' => 0, 'msg' => 'ID不能为空']);
            }
            
            $detail = Db::name('purchase_ledger')
                ->where('id', $id)
                ->find();
            
            if (!$detail) {
                return json(['code' => 0, 'msg' => '记录不存在']);
            }
            
            // 格式化数据
            $detail['is_invoiced'] = (string)$detail['is_invoiced'];
            $detail['is_paid'] = (string)$detail['is_paid'];
            $detail['arrival_date'] = date('Y-m-d', strtotime($detail['arrival_date']));
            if ($detail['payment_date']) {
                $detail['payment_date'] = date('Y-m-d', strtotime($detail['payment_date']));
            }
            
            return json([
                'code' => 1,
                'msg' => 'success',
                'data' => $detail
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => '获取详情失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }
    
    /**
     * 获取采购统计信息
     */
    public function statistics(Request $request): Json
    {
        try {
            // 总记录数
            $totalCount = Db::name('purchase_ledger')->count();
            
            // 已开票数量
            $invoicedCount = Db::name('purchase_ledger')
                ->where('is_invoiced', 1)
                ->count();
            
            // 已付款数量
            $paidCount = Db::name('purchase_ledger')
                ->where('is_paid', 1)
                ->count();
            
            // 本月新增
            $monthCount = Db::name('purchase_ledger')
                ->whereTime('create_time', 'month')
                ->count();
            
            return json([
                'code' => 1,
                'msg' => 'success',
                'data' => [
                    'total_count' => $totalCount,
                    'invoiced_count' => $invoicedCount,
                    'paid_count' => $paidCount,
                    'month_count' => $monthCount,
                    'invoiced_rate' => $totalCount > 0 ? round($invoicedCount / $totalCount * 100, 2) : 0,
                    'paid_rate' => $totalCount > 0 ? round($paidCount / $totalCount * 100, 2) : 0
                ]
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => '获取统计信息失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }
}
